#include <iostream>
#include <pthread.h>

pthread_mutex_t mutexA = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutexB = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condA = PTHREAD_COND_INITIALIZER;
pthread_cond_t condB = PTHREAD_COND_INITIALIZER;

// flagA flagB是互斥的两个变量，用于控制线程的交替执行
int flagA = 0, flagB = 0;
void *threadA(void *arg)
{
  while (true)
  {
    pthread_mutex_lock(&mutexA);
    // 检查线程B是否在打印
    while (flagB == 1)
    {
      pthread_cond_wait(&condA, &mutexA);
    }
    // 打印
    std::cout << "我是线程A" << std::endl;
    // A已打印
    flagA = 1;
    // B可以打印
    flagB = 1;
    // 告诉线程B，条件已经改变
    pthread_cond_signal(&condB);
    pthread_mutex_unlock(&mutexA);
  }

  return nullptr;
}
void *threadB(void *arg)
{
  while (true)
  {
    pthread_mutex_lock(&mutexB);
    // 检查线程A是否在打印
    while (flagA == 0)
    {
      pthread_cond_wait(&condB, &mutexB);
    }
    // 打印
    std::cout << "我是线程B" << std::endl;
    // B已打印
    flagB = 0;
    // A可以打印
    flagA = 0;
    // 告诉线程A，条件已经改变
    pthread_cond_signal(&condA);
    pthread_mutex_unlock(&mutexB);
  }

  return nullptr;
}
int main()
{
  pthread_t tidA, tidB;
  pthread_create(&tidA, nullptr, threadA, nullptr);
  pthread_create(&tidB, nullptr, threadB, nullptr);

  pthread_join(tidA, nullptr);
  pthread_join(tidB, nullptr);
  return 0;
}
